import { createContext, useContext, useState, useEffect, ReactNode, useCallback } from 'react';
import { toast } from 'sonner';
import { WaterDB, dbService } from '@/lib/db';

// 定义喝水记录接口
export interface WaterRecord {
  id: string;
  amount: number; // 毫升
  type: string; // 水的类型，如"白开水"、"咖啡"等
  timestamp: Date;
}

// 定义上下文接口
interface WaterIntakeContextType {
  dailyGoal: number;
  setDailyGoal: (goal: number) => void;
  records: WaterRecord[];
  addRecord: (amount: number, type: string) => void;
  totalIntake: number;
  goalProgress: number;
  showRecordModal: boolean;
  setShowRecordModal: (show: boolean) => void;
  showGoalModal: boolean;
  setShowGoalModal: (show: boolean) => void;
}

// 创建上下文
const WaterIntakeContext = createContext<WaterIntakeContextType | undefined>(undefined);

// 预设喝水类型和对应的毫升数
export const PRESET_WATER_TYPES = [
  { name: '白开水', amount: 150 },
  { name: '咖啡', amount: 450 },
  { name: '茶', amount: 300 },
  { name: '果汁', amount: 250 },
  { name: '牛奶', amount: 200 },
];

// 提供者组件
export const WaterIntakeProvider = ({ children }: { children: ReactNode }) => {
  // 从本地存储加载数据或使用默认值
  const [dailyGoal, setDailyGoal] = useState<number>(2000); // 默认2000ml
  const [records, setRecords] = useState<WaterRecord[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  
  const [showRecordModal, setShowRecordModal] = useState<boolean>(false);
  const [showGoalModal, setShowGoalModal] = useState<boolean>(false);

  // 计算今日总喝水量
  const totalIntake = records
    .filter(record => {
      const recordDate = new Date(record.timestamp);
      const today = new Date();
      return (
        recordDate.getDate() === today.getDate() &&
        recordDate.getMonth() === today.getMonth() &&
        recordDate.getFullYear() === today.getFullYear()
      );
    })
    .reduce((sum, record) => sum + record.amount, 0);

  // 计算目标进度百分比
  const goalProgress = Math.min(100, (totalIntake / dailyGoal) * 100);

  // 从本地存储加载数据
  useEffect(() => {
    try {
      setIsLoading(true);
      const db = dbService;
      
      // 加载每日目标
      const goal = db.getDailyGoal();
      setDailyGoal(goal);
      
      // 加载记录
      const loadedRecords = db.getRecords();
      setRecords(loadedRecords);
    } catch (error) {
      console.error('Failed to load data from storage:', error);
      toast.error('加载数据失败，请刷新页面重试');
    } finally {
      setIsLoading(false);
    }
  }, []);

  // 使用useCallback确保函数引用稳定
  const saveDailyGoal = useCallback((goal: number) => {
    try {
      const db = dbService;
      db.setDailyGoal(goal);
      setDailyGoal(goal);
    } catch (error) {
      console.error('Failed to save daily goal:', error);
      toast.error('保存目标失败，请重试');
    }
  }, []);

  // 添加新的喝水记录
  const addRecord = useCallback((amount: number, type: string) => {
    if (amount <= 0) {
      toast.error('请输入有效的水量');
      return;
    }
    
    try {
      const db = dbService;
      const newRecord: WaterRecord = {
        id: Date.now().toString(),
        amount,
        type,
        timestamp: new Date()
      };
      
      // 保存到本地存储
      db.addRecord(newRecord);
      
      // 更新状态
      setRecords(prev => [newRecord, ...prev]);
      setShowRecordModal(false);
      toast.success(`已添加 ${amount}ml ${type}`);
    } catch (error) {
      console.error('Failed to add record:', error);
      toast.error('保存记录失败，请重试');
    }
  }, [setShowRecordModal]);

  return (
    <WaterIntakeContext.Provider
      value={{
        dailyGoal,
        setDailyGoal: saveDailyGoal,
        records,
        addRecord,
        totalIntake,
        goalProgress,
        showRecordModal,
        setShowRecordModal,
        showGoalModal,
        setShowGoalModal
      }}
    >
      {children}
    </WaterIntakeContext.Provider>
  );
};

// 自定义hook方便使用上下文
export const useWaterIntake = () => {
  const context = useContext(WaterIntakeContext);
  if (context === undefined) {
    throw new Error('useWaterIntake must be used within a WaterIntakeProvider');
  }
  return context;
};